import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store"
Vue.use(VueRouter);

export const routesDefault = [{
        path: "/login",
        name: "Login",
        component: () =>
            import ("@/views/login"),
    },
    {
        name: 'Home',
        path: '/',
        component: () =>
            import ('@/layout'),
        redirect: '/dashbord',
        children: [{
            name: 'Dashbord',
            path: '/dashbord',
            component: () =>
                import ('@/views/dashbord') // 路由懒加载
        }]
    },
];

if (sessionStorage.getItem('localRouter')) {
    let localRouter = JSON.parse(sessionStorage.getItem('localRouter'))
    console.log(localRouter);
    localRouter.component = () =>
        import ('@/layout')
    localRouter.children.forEach(element => {
        console.log(element);
        if (element.fname) {
            element.component = () =>
                import (`@/views/${element.fname}${element.path}.vue`)
        } else {
            element.component = () =>
                import (`@/views${element.path}`)
        }
    })
    routesDefault[1] = localRouter
}

const router = new VueRouter({
    routes: routesDefault
});

//路由前置守卫
router.beforeEach((to, _, next) => {
    console.log(to.path);

    if (to.path === '/login') {
        next()
    } else {
        const token = store.getters.token
        if (token) {
            next()
        } else {
            next('/login')
        }
    }
})


export default router;